package org.keyczar.rsa;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Utility for generating a {@link java.security.Signature} compatible algorithm name.
 */
class SignatureAlgorithm {
  private static final String DEFAULT_ALGORITHM = "SHA256";
  private static final Set<String> SUPPORTED_ALGORITHMS = getSupportedAlgorithms();
  private static final Set<String> SUPPORTED_MGFS = getSupportedMgfs();
  
  static String getSignatureAlgorithm(String signatureAlgorithm, String mgf) {
    if (signatureAlgorithm != null && !SUPPORTED_ALGORITHMS.contains(signatureAlgorithm)) {
      throw new IllegalArgumentException("Unsupported signature algorithm " + signatureAlgorithm);
    }
    if (mgf != null && !SUPPORTED_MGFS.contains(mgf)) {
      throw new IllegalArgumentException("Unsupported MGF " + mgf);
    }
    StringBuilder algorithm = new StringBuilder();
    algorithm.append(signatureAlgorithm == null ? DEFAULT_ALGORITHM : signatureAlgorithm)
      .append("withRSA");
    if (mgf != null) {
      algorithm.append("and")
        .append(mgf);
    }
    return algorithm.toString();
  }
  
  private static Set<String> getSupportedAlgorithms() {
    Set<String> algos = new HashSet<String>();
    algos.add("SHA1");
    algos.add("SHA256");
    algos.add("SHA384");
    algos.add("SHA512");
    algos.add("MD2");
    algos.add("MD5");
    return Collections.unmodifiableSet(algos);
  }
  
  private static Set<String> getSupportedMgfs() {
    Set<String> functions = new HashSet<String>();
    functions.add("MGF1");
    return Collections.unmodifiableSet(functions);
  }
}
